﻿using System.Collections.Generic;
using UnityEngine;

#if UNITY_EDITOR
using UnityEditor;
#endif

namespace CWM.Skinn.FFD
{
	[ExecuteInEditMode] [RequireComponent(typeof(MeshFilter))] [RequireComponent(typeof(MeshRenderer))]
    public class LatticeMarker : MonoBehaviour
    {
        private static class LatticeColor
        {
            internal static readonly Color HiddenColor = new Color(0f, 0f, 0f, 0.01234f);
            internal static readonly Color SelectedColor = new Color(0f, 1f, 0f, 0.5f);
            internal static readonly Color NormalColor = new Color(0f, 1f, 1f, 0.5f);
        }

        [HideInInspector] public LatticeDeformer lattice = null;
        [HideInInspector] public int weightCount = 0;
        [HideInInspector] public List<Vector2> weights = new List<Vector2>(0);
        [HideInInspector] public LatticeMarker[] adjancentMarkers = new LatticeMarker[0];
        [HideInInspector] public int[] adjancentIndices = new int[0];

        public MeshFilter GetMeshFilter { get; private set; }

        private void Start() { }

        private void Awake()
        {
			GetMeshFilter = GetComponent<MeshFilter> ();
			HideMarkerFlags ();
		}

        private void OnDrawGizmos()
        {
#if UNITY_EDITOR
            var gizmosColor = Gizmos.color;
            if (System.Array.Find(Selection.transforms, (x) => { return x == this.transform; })) Gizmos.color = LatticeColor.SelectedColor;
            else if (weightCount < 1) Gizmos.color = LatticeColor.HiddenColor;
            else Gizmos.color = LatticeColor.NormalColor;
            for (int i = 0; i < adjancentMarkers.Length; i++)
            { var end = adjancentMarkers[i]; if (end) Gizmos.DrawLine(transform.position, end.transform.position); }
            Gizmos.color = gizmosColor;
#endif
        }

        private void OnDestroy() { ShowMarkerFlags(); }

        private void HideMarkerFlags()
        {
			GetComponent<MeshFilter> ().hideFlags = HideFlags.HideInInspector;
			GetComponent<MeshRenderer> ().hideFlags = HideFlags.HideInInspector;
		}

        private void ShowMarkerFlags()
        {
			GetComponent<MeshFilter> ().hideFlags = HideFlags.None;
			GetComponent<MeshRenderer> ().hideFlags = HideFlags.None;
		}
	}
}